﻿using System.Configuration;
using System.Data.Common;
using System.Linq;
using System.Data;

namespace UltraDBFactoring
{
    /// <summary>
    /// Class responsible for Connection Factory.
    /// </summary>
    public class ConnectionFactoryDB
    {
        /// <summary>
        /// Given a connection string, create the DbProviderFactory and the DbConnection.
        /// </summary>
        /// <param name="connectionName">The name of the connection.</param>
        /// <returns>Returns the DbConnection if success; null on fail.</returns>
        public static DbProviderFactory CreateDataBaseObject(string connectionName)
        {
            ConnectionStringSettings connectionString = GetConnectionStringByName(connectionName);
            DbProviderFactory factory = null;

            if (connectionString != null)
            {
                try
                {
                    factory = DbProviderFactories.GetFactory(connectionString.ProviderName);
                }
                catch
                {
                    if (factory != null)
                    {
                        factory = null;
                    }
                }
            }

            return factory;
        }

        /// <summary>
        /// Gets the connection string given its connection name.
        /// Assume uma string de conexão por provedor no arquivo de configuração.
        /// </summary>
        /// <param name="connectionName">The name of the connection.</param>
        /// <returns>Returns a connection string if success; null on fail.</returns>
        public static ConnectionStringSettings GetConnectionStringByName(string connectionName)
        {
            if (ConfigurationManager.ConnectionStrings != null)
            {
                ConnectionStringSettings css = (from n in ConfigurationManager.ConnectionStrings.Cast<System.Configuration.ConnectionStringSettings>()
                                                where n.Name == connectionName
                                                select n).FirstOrDefault();

                return css;
            }

            return null;
        }
    }
}
